package com.cube.truthseer.common.mybatis.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cube.truthseer.common.security.AuthUser;
import com.cube.truthseer.common.security.context.UserContext;
import com.cube.truthseer.common.utils.SnowFlakeUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private UserContext userContext;

    @Override
    public void insertFill(MetaObject metaObject) {
        AuthUser authUser = userContext.getLoginUser();
        //有创建时间字段，切字段值为空
        if (metaObject.hasGetter("create_time")) {
            this.setFieldValByName("create_time", LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasGetter("id")) {
            //如果已经配置id，则不再写入
            if (metaObject.getValue("id") == null) {
                this.setFieldValByName("id", String.valueOf(SnowFlakeUtil.getId()), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        AuthUser authUser = userContext.getLoginUser();
        if (authUser != null) {
            this.setFieldValByName("updateBy", authUser.getUsername(), metaObject);
        } else {
            this.setFieldValByName("updateBy", "SYSTEM", metaObject);
        }
        this.setFieldValByName("update_time", LocalDateTime.now(), metaObject);
    }
}